<template>
  <div class="tag-bind-container">
    <div class="header">
      <div>
        <el-icon class="back-icon" @click="goBack">
          <ArrowLeft />
        </el-icon>
      </div>
      <div>标签解绑</div>
      <div></div>
    </div>

    <div class="form-container">
      <el-row :gutter="20">
        <el-col :offset="0" :span="24">
          <span>标签编码:</span>
          <span>
            <p style="color: #f56c6c; margin-bottom: 8px; font-size: 14px">请将标签靠近手机背面</p>
            A-A001
          </span>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :offset="0" :span="24">
          <span>绑定目标:</span>
          <span>假台车</span>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :offset="0" :span="24">
          <span>项目号:</span>
          <span>A-A246</span>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :offset="0" :span="24">
          <span>车辆号:</span>
          <span>010-01</span>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :offset="0" :span="24">
          <span>WBS:</span>
          <span>A-{{ form.projectId }}-P-{{ form.carList }}-{{ form.carVehicle }}</span>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :offset="0" :span="24">
          <span>标签位置:</span>
          <span>东</span>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :offset="0" :span="24">
          <span>车型:</span>
          <el-radio v-model="radio1" :value="0" disabled>中间车</el-radio>
          <el-select v-model="form.carPositions" clearable placeholder="" style="width: 30%">
            <el-option v-for="position in carPositions" :key="position.value" :label="position.label" :value="position.value" />
          </el-select>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-if="form.bindingTarget == 1">
        <el-col :offset="0" :span="24">
          <span>迁车信息:</span>
          <span>迁车台1</span>
        </el-col>
      </el-row>
    </div>

    <div class="button-container">
      <el-button :disabled="scanDisabled" :loading="scanLoading" class="scan-button" type="primary" @click="scanTag"> 扫描标签 </el-button>
      <el-button :loading="loading" class="submit-button" type="primary" @click="handleSubmit"> 确定 </el-button>
    </div>
  </div>
</template>

<script lang="ts" name="tagUnbind" setup>
import { listSapOrder } from '@/api/painting/sapOrder';
import { SapOrderForm, SapOrderQuery, SapOrderVO } from '@/api/painting/sapOrder/types';
import { ElMessageBoxOptions } from 'element-plus/es/components/message-box/src/message-box.type';
import { TagUnbindFormData, TagUnbindPositions } from '@/api/tagbind/types';

const router = useRouter();

const form = ref<TagUnbindFormData>({
  id: '',
  projectId: '',
  carList: '',
  carVehicle: '',
  tagPosition: 'n1',
  carriageTypeId: 1,
  tagCode: '',
  bindingTarget: 0,
  moveTheCar: '',
  carPositions: '1'
});

const loading = ref(false);
const radio1 = ref(0);
const scanLoading = ref(false);
const scanDisabled = ref(false);

const projectOptions = ref<SapOrderVO[]>([]);
const queryParams = ref<SapOrderQuery>({
  pageNum: 1,
  pageSize: 10,
  bindStatus: 0
});
const tagPositions = ref<any[]>([
  { value: 'n1', label: '南1' },
  { value: 'n2', label: '南2' }
]);

const carPositions = ref<any[]>([
  { value: '1', label: '朝东' },
  { value: '2', label: '朝西' }
]);
const rules: ElFormRules = {
  tagCode: [{ required: true, message: '请扫描标签编号', trigger: 'change' }],
  projectId: [{ required: true, message: '请选择项目号', trigger: 'change' }],
  carriageCode: [{ required: true, message: '请输入车辆号', trigger: 'blur' }],
  tagPosition: [{ required: true, message: '请选择标签位置', trigger: 'change' }],
  carriageTypeId: [{ required: true, message: '请选择车厢类型', trigger: 'change' }]
};

const getList = async () => {
  loading.value = true;
  const res = await listSapOrder(queryParams.value);
  projectOptions.value = res.rows;
  loading.value = false;
};

const goBack = () => {
  router.back();
};

const handleSubmit = () => {
  if (!form.value.projectId) {
    ElMessage.warning('请选择项目号');
    return;
  }
  if (!form.value.carriageCode) {
    ElMessage.warning('请输入车辆号');
    return;
  }
  if (!form.value.tagPosition) {
    ElMessage.warning('请选择标签位置');
    return;
  }

  loading.value = true;
  setTimeout(() => {
    ElMessage.success('绑定成功');
    loading.value = false;
  }, 1000);
};
// 声明window.Android、window.callJsFunction类型，避免TS报错
// 处理原生消息
function handleNativeMessage(jsonData: string) {
  try {
    ElMessage.success('jsonData:' + jsonData);
    const data = JSON.parse(jsonData);
    form.value.tagCode = data[1];
    if (scanTimeout) {
      clearTimeout(scanTimeout);
      scanTimeout = null;
    }
    scanLoading.value = false;
    scanDisabled.value = false;
    if (window.Android && typeof window.Android.stopRead === 'function') {
      window.Android.stopRead();
    }
    ElMessage.success('标签扫描成功');
  } catch (e) {
    console.error('[调试] 解析原生消息失败:', e, jsonData);
  }
}

// 主动调用Android的scanTag方法
function scanTag() {
  if (scanDisabled.value) return;

  scanLoading.value = true;
  scanDisabled.value = true;
  if (window.Android && typeof window.Android.startRead === 'function' && typeof window.Android.stopRead === 'function') {
    window.Android.startRead();
    // 启动读卡后等待一段时间再读取
    ElMessage.success('readRfid:' + window.Android.readRfid);
    setTimeout(() => {
      if (window.Android && typeof window.Android.readRfid === 'function') {
        ElMessage.success('开始读卡readRfid');
        window.Android.readRfid();
        ElMessage.success('正在读卡readRfid');
      } else {
        ElMessage.warning('未初始化读卡模块');
        scanLoading.value = false;
        scanDisabled.value = false;
        window.Android.stopRead();
      }
    }, 1000); // 2秒后调用read
    scanTimeout = setTimeout(() => {
      if (scanLoading.value) {
        ElMessage.warning('未检测到标签，请重试');
        scanLoading.value = false;
        scanDisabled.value = false;
        window.Android.stopRead();
      }
    }, 3000);
  } else {
    form.value.tagCode = 'MOCK_TAG_' + Math.floor(Math.random() * 1000000);
    scanLoading.value = false;
    scanDisabled.value = false;
    ElMessage.success('标签扫描成功(未处于Android环境)');
  }
}

let scanTimeout: ReturnType<typeof setTimeout> | null = null;
let inactivityTimer: ReturnType<typeof setTimeout> | null = null;
const INACTIVITY_LIMIT = 5 * 60 * 1000;

function resetInactivityTimer() {
  if (inactivityTimer) clearTimeout(inactivityTimer);
  inactivityTimer = setTimeout(() => {
    ElMessage.warning('长时间无操作，已自动返回上一页');
    router.back();
  }, INACTIVITY_LIMIT);
}

function addInactivityListeners() {
  const events = ['click', 'touchstart', 'keydown'];
  events.forEach((event) => {
    window.addEventListener(event, resetInactivityTimer, true);
  });
}

function removeInactivityListeners() {
  const events = ['click', 'touchstart', 'keydown'];
  events.forEach((event) => {
    window.removeEventListener(event, resetInactivityTimer, true);
  });
}

onMounted(() => {
  getList();
  window.callJsFunction = handleNativeMessage;
  if (window.Android && typeof window.Android.powerOn === 'function') {
    window.Android.powerOn();
  }
  addInactivityListeners();
  resetInactivityTimer();
});

onBeforeUnmount(() => {
  if (window.Android && typeof window.Android.powerOff === 'function') {
    window.Android.powerOff();
  }
  window.callJsFunction = undefined;
  if (inactivityTimer) clearTimeout(inactivityTimer);
  removeInactivityListeners();
});
</script>

<style lang="scss" scoped>
.tag-bind-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background-color: #f5f5f5;
  // max-width: 800px;
  // margin: 0 auto;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background-color: #409eff;
    color: white;
    font-size: 18px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

    .back-icon {
      font-size: 24px;
      cursor: pointer;
    }

    .logout-btn {
      color: white;
      font-size: 16px;
    }
  }

  .form-container {
    // flex: 1;
    overflow-y: auto;
    padding: 20px;
    height: calc(100% - 108px);

    .el-row {
      align-items: center;

      .el-col {
        font-size: 16px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        padding: 15px;
        display: flex;
        align-items: center;
        justify-content: flex-start;

        span:nth-child(1) {
          width: 80px;
          display: inline-block;
        }

        span:nth-child(2) {
          padding-left: 10px;
          color: #000;
        }

        :deep(.el-radio__label) {
          color: #000 !important;
        }
      }
    }
  }

  .button-container {
    display: flex;
    flex-direction: row;
    gap: 16px;
    margin-top: 32px;
    margin-bottom: 16px;
    justify-content: center;
    align-items: center;
    padding: 0 10px;

    .scan-button,
    .submit-button {
      width: 48%;
      height: 48px;
      font-size: 16px;
      font-weight: 600;
      border-radius: 24px;
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.08);
      transition: background 0.2s, box-shadow 0.2s;
    }

    .scan-button {
      background: #fff;
      color: #409eff;
      border: 1.5px solid #409eff;
    }

    .scan-button:hover {
      background: #ecf5ff;
      color: #1867c0;
      border-color: #1867c0;
    }

    .submit-button {
      background: #409eff;
      color: #fff;
      border: none;
    }

    .submit-button:hover {
      background: #1867c0;
      color: #fff;
    }
  }
}
</style>
